/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.portal.common.impl
 */
package com.apache.portal.common.connector.impl;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apache.api.vo.ParamsVo;
import com.apache.portal.common.annotion.BeanFactory;
import com.apache.portal.common.connector.InterceptorAdapter;

/**
 * description:  
 * @author Administrator 创建时间：2016-10-25  
 */
public class AdapterFactory {

	private static AdapterFactory instance;
	private Map<String, InterceptorAdapter> adapters = new HashMap<String, InterceptorAdapter>();

	private AdapterFactory() {
		adapters.put("createInfo", new SetCreateInfoAdapterImpl());
		adapters.put("setReqParam", new SetReqParamAdapterImpl());
	}

	public static AdapterFactory getInstance() {
		if (null == instance) {
			instance = new AdapterFactory();
		}
		return instance;
	}

	public InterceptorAdapter getAdapter(String key) {
		return (InterceptorAdapter) BeanFactory.getInstance().getBeans(key);
		//return adapters.get(key);
	}

	public Map getReqParamForBefor(String keys, Map param, HttpServletRequest request, HttpServletResponse response) {
		return getRequestParam("before", keys, param, request, response);
	}

	public Map getReqParamForAfter(String keys, Map param, HttpServletRequest request, HttpServletResponse response) {
		return getRequestParam("after", keys, param, request, response);
	}

	public Map getReqParam(String keys, Map param, HttpServletRequest request, HttpServletResponse response) {
		return getRequestParam("center", keys, param, request, response);
	}

	private Map getRequestParam(String methodType, String keys, Map param, HttpServletRequest request,
			HttpServletResponse response) {
		ParamsVo vo = new ParamsVo();
		try {
			String key[] = keys.split(",");
			vo.setParams(param);
			for (int i = 0; i < key.length; i++) {
				if ("before".equals(methodType)) {
					getAdapter(key[i]).beforPreHandle(request, response, vo);
					//	adapters.get(key[i]).beforPreHandle(request, response, vo);
				} else if ("center".equals(methodType)) {
					getAdapter(key[i]).preHandle(request, response, vo);
					//adapters.get(key[i]).preHandle(request, response, vo);
				} else if ("after".equals(methodType)) {
					getAdapter(key[i]).afterHandle(request, response, vo);
					//adapters.get(key[i]).afterHandle(request, response, vo);
				}
			}
			return vo.getParams();
		} catch (Exception e) {
			vo.setParams("execptionMsg", e.getMessage());
		}
		return vo.getParams();
	}
}
